package org.study.util;

import okhttp3.*;
import okio.BufferedSink;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * https：//www.jianshu.com/p/da4a806e599b
 *
 * @author Administrator
 */
public final class HttpUtils {
    public static void main(String[] args) {
        String url = "http：//wwww.baidu.com";
        String host_query = "http://106.52.163.242:8123/?query=";
        String sql = "SELECT * FROM cp_d_device_signal order by create_time desc limit 100";
        getSync(host_query + sql);
        List<String> list = new ArrayList<String>() {{
            add("绑定设备123");
            add("绑定设备456");
            add("绑定设备789");
        }};
        String format = String.format("站点[%s], 车位%s, 绑定设备[%s]", 1L, list, "设备号");
        System.out.println(format);
    }

    private static final MediaType Media_Type = MediaType.parse("application/json; charset=utf-8");
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .build();

    /**
     * 异步 GET 请求：
     * 1、new OkHttpClient
     * 2、构造 Request 对象
     * 3、通过前两步中的对象构建 Call 对象
     * 4、通过 Call#enqueue(Callback) 方法来提交异步请求
     */
    public static void getAsync(String url) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()// 默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException ex) {
                // log.error("异步 GET 请求 - onFailure：{}", ex);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // log.info("异步 GET 请求 - onResponse：{}", response.body().string());
            }
        });
    }

    /**
     * 同步 GET 请求：
     * 前面几个步骤和异步方式一样，只是最后一部是通过 Call#execute() 来提交请求，注意这种方式会阻塞调用线程，所以在Android中应放在子线程中执行，否则有可能引起ANR异常，Android3.0 以后已经不允许在主线程访问网络。
     */
    public static void getSync(String url) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()// 默认就是GET请求，可以不写
                .build();
        final Call call = okHttpClient.newCall(request);
        new Thread(() -> {
            try {
                Response response = call.execute();
                // log.info("同步 GET 请求 - 响应结果：{}", response.body().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * POST方式提交String：
     * 这种方式与前面的区别就是在构造Request对象时，需要多构造一个RequestBody对象，用它来携带我们要提交的数据。在构造 RequestBody 需要指定MediaType，用于描述请求/响应 body 的内容类型
     */
    public static void post4String() {
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        String requestBody = "成都市";
        Request request = new Request.Builder()
                .url("https：//api.github.com/markdown/raw")
                .post(RequestBody.create(mediaType, requestBody))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException ex) {
                // log.error("onFailure：{}", ex);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // log.info(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    // log.info(headers.name(i) + "：" + headers.value(i));
                }
                // log.info("onResponse：{}", response.body().string());
            }
        });
    }

    /**
     * POST方式提交流
     */
    public static void post4Stream() {
        RequestBody requestBody = new RequestBody() {
            @Override
            public MediaType contentType() {
                return MediaType.parse("text/x-markdown; charset=utf-8");
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                sink.writeUtf8("成都市");
            }
        };

        Request request = new Request.Builder()
                .url("https：//api.github.com/markdown/raw")
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException ex) {
                // log.error("onFailure：{}", ex);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // log.info(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    // log.info(headers.name(i) + "：" + headers.value(i));
                }
                // log.info("onResponse：{}", response.body().string());
            }
        });
    }

    /**
     * POST提交文件
     */
    public static void post4File() {
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        OkHttpClient okHttpClient = new OkHttpClient();
        File file = new File("test.md");
        Request request = new Request.Builder()
                .url("https：//api.github.com/markdown/raw")
                .post(RequestBody.create(mediaType, file))
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException ex) {
                // log.error("onFailure：{}", ex);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // log.info(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    // log.info(headers.name(i) + "：" + headers.value(i));
                }
                // log.info("onResponse：{}", response.body().string());
            }
        });
    }

    /**
     * POST方式提交表单
     */
    public static void post4Form() {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("search", "Jurassic Park")
                .build();
        Request request = new Request.Builder()
                .url("https：//en.wikipedia.org/w/index.php")
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException ex) {
                // log.error("onFailure：{}", ex);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // log.info(response.protocol() + " " + response.code() + " " + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    // log.info(headers.name(i) + "：" + headers.value(i));
                }
                // log.info("onResponse：{}", response.body().string());
            }
        });
    }

    /**
     * POST方式提交分块请求
     */
    public static void postMultipartBody() {
        final String IMGUR_CLIENT_ID = "...";
        final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        OkHttpClient client = new OkHttpClient();
        // Use the imgur image upload API as documented at https：//api.imgur.com/endpoints/image
        MultipartBody body = new MultipartBody.Builder("AaB03x")
                .setType(MultipartBody.FORM)
                .addPart(Headers.of("Content-Disposition", "form-data; name=\"title\""),
                        RequestBody.create(null, "Square logo"))
                .addPart(Headers.of("Content-Disposition", "form-data; name=\"image\""),
                        RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
                .build();
        Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
                .url("https：//api.imgur.com/3/image")
                .post(body)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
            }
        });
    }
}
